package com.firesys.httpserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;

import com.firesys.dbhelper.SharedPreferenceUtil;
import com.firesys.dbhelper.XmlNameHelper;




import android.content.Context;



public class HttpClientServer {

    public Context context;

    public String urlAddress;

    public String request;
    
    private SharedPreferenceUtil sp;

    public HttpClientServer(Context context) {

	this.context = context;
	sp = new SharedPreferenceUtil(context);

    }

    /**
     * 创建HttpClient 并设置参数
     * 
     * @param timeout
     * @return
     */
    public HttpClient getHttpClient() {
	BasicHttpParams httpParams = new BasicHttpParams();
	// 设置请求超时时间
	HttpConnectionParams.setConnectionTimeout(httpParams, 10 * 1000);
	HttpConnectionParams.setSoTimeout(httpParams, 10 * 1000);// 设置等待数据超时时间
	// 设置 Socket 缓存大小
	HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
	HttpClient client = new DefaultHttpClient(httpParams);
	return client;
    }

    /**
     * 发送普通Http请求
     * 
     * @param user
     * @return
     */
    public String doPost(Map<String, String> map, String request,boolean b) {
	if(b){
	    geturl(request);
	}else{
	 urlAddress=request;   
	}      
	HttpPost httpPost = new HttpPost(urlAddress);
	System.out.println(urlAddress+"---------urlAddress------");
	List params = new ArrayList();
	if(map!=null||!map.isEmpty()){
	    for (String key : map.keySet()) {
		    System.out.println("key:" + key + ":value:" + map.get(key));
		    NameValuePair pair = new BasicNameValuePair(key, map.get(key));
		    params.add(pair);
		}
	}	
	HttpEntity he;
	  HttpClient hc =null;
	
	    try {
		he = new UrlEncodedFormEntity(params, "utf-8");
		  httpPost.setEntity(he);
		     hc = getHttpClient();
		    HttpResponse ht = hc.execute(httpPost);
		    if (ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			HttpEntity het = ht.getEntity();
			InputStream is = het.getContent();
			return getInputStreamString(is);
		    } else {
			
			return ""+ht.getStatusLine().getStatusCode();
		    }
		
	    } catch (UnsupportedEncodingException e) {		
		e.printStackTrace();
		//编码异常
		return "error";
	    } catch (ClientProtocolException e) {		
		e.printStackTrace();
		//网络异常
		return "error";
	    }catch(ConnectTimeoutException e){
		//连接超时
		return "error";
	    }
	    catch (IOException e) {
		
		e.printStackTrace();
		return "error";
	    }finally{
		if(hc!=null){
		    hc.getConnectionManager().shutdown();
		}
	    }
	 
	  

    }

    /**
     * 通过输入流得到返回的字符串
     * 
     * @param is
     * @return
     */
    public String getInputStreamString(InputStream is) {
	BufferedReader br = null;
	InputStreamReader isr = null;
	byte[] by = new byte[64];
	String str = "";
	String res = "";
	if (is != null) {
	    try {
		isr = new InputStreamReader(is, "utf-8");
		br = new BufferedReader(isr);
		while ((res = br.readLine()) != null) {
		    str = str + res;
		}
	    } catch (UnsupportedEncodingException e) {
		
		e.printStackTrace();
	    } catch (IOException e) {
		
		e.printStackTrace();
	    } finally {

		if (is != null) {
		    try {
			br.close();
			isr.close();
			is.close();

		    } catch (IOException e) {
			
			e.printStackTrace();
		    }
		}

	    }

	}
	return str;

    }

    /**
     * 组装请求字符串
     * 
     * @param request
     */
    public void geturl(String request) {
	StringBuffer sb = new StringBuffer("http://");
	sb.append(sp.getValue(XmlNameHelper.IP)).append(":").append(sp.getValue(XmlNameHelper.port));
	sb.append("/").append(sp.getValue(XmlNameHelper.webName)).append(request);
	this.urlAddress = sb.toString();
	
    }

}
